<template>
  <el-card class="sku-list">
    <vxe-table
      :row-config="{ height: 150 }"
      border="full"
      stripe
      :data="tableData.data"
      :loading="tableData.loading"
    >
      <vxe-column title="序号" width="80" align="center">
        <template #default="{ $rowIndex }">
          {{
            tableData.params.limit * (tableData.params.page - 1) + $rowIndex + 1
          }}
        </template>
      </vxe-column>
      <vxe-column field="skuName" title="名称" min-width="200" />

      <vxe-column field="skuDesc" title="描述" min-width="200" />
      <vxe-column title="默认图片" width="150" align="center">
        <template #default="{ row }">
          <el-image
            :src="row.skuDefaultImg"
            alt="商品图片"
            style="width: 80px; height: 80px"
          />
        </template>
      </vxe-column>
      <vxe-column field="weight" title="重量(KG)" width="120" align="right" />

      <vxe-column
        field="price"
        title="价格(元)"
        width="120"
        align="right"
        formatter="formatAmount3"
      />
      <vxe-column title="操作" width="200" align="center">
        <template #default="{ row }">
          <el-button
            v-if="row.isSale == 0"
            @click="onSale(row.id)"
            title="上架"
            type="info"
            size="small"
            :icon="Top"
            v-has="'btn.Sku.updown'"
          />
          <el-button
            v-else
            @click="cancelSale(row.id)"
            title="下架"
            type="success"
            size="small"
            :icon="Bottom"
            v-has="'btn.Sku.updown'"
          />
          <el-button
            title="修改"
            type="primary"
            size="small"
            :icon="Edit"
            @click="toUpdateSku"
            v-has="'btn.Sku.update'"
          />
          <el-button
            title="查看详情"
            type="info"
            size="small"
            :icon="InfoFilled"
            @click="showSkuInfo(row.id)"
            v-has="'btn.Sku.detail'"
          />
          <el-popconfirm
            :title="`确定删除${row.skuName}吗`"
            @confirm="deleteSku(row.id)"
          >
            <template #reference>
              <el-button
                style="margin-left: 10px"
                type="danger"
                size="small"
                :icon="Delete"
                title="删除"
                v-has="'btn.Sku.remove'"
              ></el-button>
            </template>
          </el-popconfirm>
        </template>
      </vxe-column>
    </vxe-table>

    <!--分页-->
    <el-pagination
      :current-page="tableData.params.page"
      :total="tableData.total"
      :page-size="tableData.params.limit"
      :page-sizes="[10, 20, 30]"
      style="padding: 20px 0; text-align: center"
      layout="prev, pager, next, jumper, ->, sizes, total"
      @current-change="getSkuList($event)"
      @size-change="getSkuList(1, $event)"
    />
    <!--分页end-->

    <!--sku详情的抽屉drawer组件-->
    <el-drawer
      v-model="skuData.isShowSkuInfo"
      :with-header="false"
      size="50%"
      :before-close="handleClose"
    >
      <div v-loading="skuData.isLoading">
        <el-row>
          <el-col :span="5">名称</el-col>
          <el-col :span="16">{{ skuData.skuInfo?.skuName }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="5">描述</el-col>
          <el-col :span="16">{{ skuData.skuInfo?.skuDesc }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="5">价格</el-col>
          <el-col :span="16">{{ skuData.skuInfo?.price }}</el-col>
        </el-row>

        <el-row>
          <el-col :span="5">平台属性</el-col>
          <el-col :span="18">
            <div
              v-if="
                skuData.skuInfo?.skuAttrValueList &&
                skuData.skuInfo?.skuAttrValueList.length > 0
              "
            >
              <el-tag
                type="success"
                style="margin-right: 5px"
                v-for="value in skuData.skuInfo?.skuAttrValueList"
                :key="value.id"
              >
                {{ value.attrName + "-" + value.valueName }}
              </el-tag>
            </div>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="5">销售属性</el-col>
          <el-col :span="18">
            <div
              v-if="
                skuData.skuInfo?.skuSaleAttrValueList &&
                skuData.skuInfo?.skuSaleAttrValueList.length > 0
              "
            >
              <el-tag
                type="success"
                style="margin-right: 5px"
                v-for="value in skuData.skuInfo?.skuSaleAttrValueList"
                :key="value.id"
              >
                {{ value.saleAttrName + "-" + value.saleAttrValueName }}
              </el-tag>
            </div>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="5">商品图片</el-col>
          <el-col :span="16">
            <el-carousel
              class="sku-carousel"
              trigger="click"
              height="400px"
              style="width: 400px"
            >
              <el-carousel-item
                v-for="item in skuData.skuInfo?.skuImageList"
                :key="item.id"
              >
                <img
                  :src="item.imgUrl"
                  alt=""
                  style="width: 100%; height: 100%"
                />
              </el-carousel-item>
            </el-carousel>
          </el-col>
        </el-row>
      </div>
    </el-drawer>
    <!--sku详情的抽屉drawer组件end-->
  </el-card>
</template>

<script lang="ts">
export default {
  name: "Sku",
};
</script>

<script lang="ts" setup>
import { ElMessage } from "element-plus";
import { Top, Bottom, Edit, InfoFilled, Delete } from "@element-plus/icons-vue";
import { reactive, onMounted, toRefs } from "vue";
import {
  getSkuListApi,
  deleteSkuApi,
  onSaleApi,
  cancelSaleApi,
  getSkuInfoApi,
} from "@/api/product/sku";
import type { SkuListModel, SkuModel } from "@/types";
// 引入格式化金额的函数
import "@/utils/vxe-format";

// 定义表格数据类型模型
interface TableDataState {
  tableData: {
    data: SkuListModel;
    total: number;
    loading: boolean;
    params: {
      page: number;
      limit: number;
    };
  };
}
// 定义表格响应式数据
const tableDataState = reactive<TableDataState>({
  tableData: {
    data: [], // 表格数据
    total: 0, // 总条数
    loading: false, // 加载中
    params: {
      page: 1, // 当前页
      limit: 10, // 每页条数
    },
  },
});
// 解构tabelData
const { tableData } = toRefs(tableDataState);

// 定义接收到的要展示的sku详情信息数据模型
interface SkuState {
  skuData: {
    skuInfo: SkuModel | undefined;
    // 控制详情信息（Drawer组件）的显示与隐藏
    isShowSkuInfo: boolean;
    isLoading: boolean;
  };
}

// 定义接收到的sku详情数据
const skuState = reactive<SkuState>({
  skuData: {
    // 初始值为undefined
    skuInfo: undefined,
    isShowSkuInfo: false,
    isLoading: false,
  },
});
// 获取sku详情信息的请求
const showSkuInfo = async (id: number) => {
  skuState.skuData.isShowSkuInfo = true;
  skuState.skuData.isLoading = true;
  const result = await getSkuInfoApi(id);
  skuState.skuData.skuInfo = result;
  skuState.skuData.isLoading = false;
};

// 解构skuData
const { skuData } = toRefs(skuState);
// 初始化获取sku列表
onMounted(() => {
  // 获取sku列表信息
  getSkuList();
});
// 异步获取指定页码的sku列表
const getSkuList = async (
  page: number = tableDataState.tableData.params.page,
  limit: number = tableDataState.tableData.params.limit
) => {
  tableDataState.tableData.params.page = page;
  tableDataState.tableData.params.limit = limit;
  tableDataState.tableData.loading = true;
  // 发送请求获取数据
  const result = await getSkuListApi(page, limit);
  const { records, total } = result;
  // 保存sku数据
  tableDataState.tableData.data = records;
  // 总条数
  tableDataState.tableData.total = total;
  tableDataState.tableData.loading = false;
};

// 删除sku
const deleteSku = async (skuId: number) => {
  await deleteSkuApi(skuId);
  ElMessage.success("删除sku成功");
  let totalPage; //总页数
  // 向上取整（总条数/每页条数）
  totalPage = Math.ceil(
    (tableDataState.tableData.total - 1) / tableDataState.tableData.params.limit
  );
  // 判断当前页
  // 当前页大于总页数用总页数
  let currentPage =
    tableDataState.tableData.params.page > totalPage
      ? totalPage
      : tableDataState.tableData.params.page;
  // 当前页小于1，则是1，大于1，则是当前页（但不会大于总页数）
  tableDataState.tableData.params.page = currentPage < 1 ? 1 : currentPage; // 当前页数
  getSkuList(tableDataState.tableData.params.page);
};

// 对指定SKU进行上架的请求
const onSale = async (skuId: number) => {
  await onSaleApi(skuId);
  ElMessage({
    type: "success",
    message: "上架成功",
  });
  getSkuList();
};
// 对指定SKU进行下架的请求
const cancelSale = async (skuId: number) => {
  await cancelSaleApi(skuId);
  ElMessage({
    type: "success",
    message: "下架成功",
  });
  getSkuList();
};
// 关闭 Drawer的回
const handleClose = (done: () => void) => {
  skuState.skuData.skuInfo = undefined;
  done();
};

// 修改sku
const toUpdateSku = () => {
  ElMessage.info("正在拼命开发中");
};
</script>

<style lang="scss" scoped>
.el-row {
  margin: 10px 0;
  .el-col-5 {
    text-align: right;
    margin-right: 20px;
    font-size: 20px;
  }
}
// 修改第三方组件样式
// 修改carousel的指示器的样式
:deep(.el-carousel__indicator) {
  button {
    background-color: lightblue;
  }
  &.is-active {
    button {
      background-color: skyblue;
    }
  }
}
</style>
